<template>
  <div class="space">
    <!-- 弹窗 -->
    <div class="dialog">
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-form
          class="form"
          :model="space"
          :rules="rules"
          label-position="right"
          label-width="100px"
          ref="form"
        >
          <el-form-item label="选择位置" prop="parentID">
            <el-cascader
              v-model="spacesModel"
              :props="spaceProps"
              clearable
              :options="options"
              @change="spaceChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="位置名称" prop="name">
            <el-input v-model="space.name" />
          </el-form-item>
          <el-form-item label="位置描述" prop="description">
            <el-input type="textarea" v-model="space.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelClick">取 消</el-button>
          <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 查看所有设备 -->
    <div class="children">
      <el-dialog
        :title="children.title"
        :visible.sync="children.visible"
        width="80%"
      >
        <el-table
          style="width: 100%"
          row-key="id"
          border
          :data="childrenTable"
          :header-cell-style="{ 'background-color': '#EEEEEE' }"
        >
          <el-table-column prop="name" label="设备名称"></el-table-column>
          <el-table-column
            prop="reportInterval"
            label="报道间隔"
          ></el-table-column>
          <el-table-column
            prop="offlineInterval"
            label="离线间隔"
          ></el-table-column>
          <el-table-column prop="serialNumber" label="串口号"></el-table-column>
          <el-table-column prop="installDate" label="注册日期">
          </el-table-column>
          <el-table-column
            prop="description"
            label="设备描述"
          ></el-table-column>
          <el-table-column prop="picture" label="图片"></el-table-column>
          <el-table-column
            prop="pictureMime"
            label="图片类型"
          ></el-table-column>
          <el-table-column prop="statusID" label="设备状态">
            <template slot-scope="scope">
              {{ statuses[scope.row.statusID].label }}
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <!-- 权限弹窗 -->
    <div class="perm">
      <el-dialog
        :title="perm.title"
        :visible.sync="perm.visible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-card>
          <el-form
            class="form"
            :model="detail"
            :rules="rules"
            label-position="right"
            ref="permform"
          >
            <el-form-item prop="id">
              <el-transfer
                :titles="['未关联群组', '已关联群组']"
                style="display: inline-block"
                v-model="detail.select"
                :data="groups"
                @right-check-change="handleRightChange"
              ></el-transfer>
            </el-form-item>
            <el-form-item prop="">
              <div v-for="(item, index) in permissions" :key="index">
                <span class="border">{{ item.label }} &nbsp; &nbsp;</span>
                <el-radio-group v-model="item.hasPerm" @change="handleRadioChange">
                  <el-radio :label="1">允许</el-radio>
                  <el-radio :label="0">拒绝</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 选择框 -->
    <div class="header">
      <el-form :inline="true" size="small" label-width="84px">
        <el-form-item label="位置名称">
          <el-input v-model="search.name" placeholder="位置名称" />
        </el-form-item>
        <el-form-item label="上级位置">
          <el-cascader
              v-model="spaces"
              :props="spaceProps"
              :options="options"
              clearable
              @change="selectChange"
            ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="getDatas(0, 0)">查询</el-button>
          <el-button type="primary" size="mini" @click="addData">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-card>
        <el-table
          style="width: 100%"
          row-key="id"
          border
          :data="datas"
          :header-cell-style="{ 'background-color': '#EEEEEE' }">
          <el-table-column prop="name" label="位置名称"></el-table-column>
          <el-table-column
            prop="description"
            label="位置描述"
          ></el-table-column>
          <el-table-column prop="statusID" label="位置状态">
            <template slot-scope="scope">
              {{ statuses[scope.row.statusID].label }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间">
            <template slot-scope="scope">
              {{ dateFormat(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showDialog(scope.row)" type="text" size="small">修改</el-button>
              <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
              <el-button type="text" size="small" @click="lookChildren(scope.row)">查看位置</el-button>
              <el-button @click="handlePermission(scope.row)" type="text" size="small">设置权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            :total="total"
            :current-page.sync="pageNo"
            :page-sizes="[10, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    <div class="footer"></div>
  </div>
</template>

<script>
import { getSpaces, addSpace, updateSpace, deleteSpace } from "@/api/space";
import { getPermissions } from "@/api/permission";
import { getEquipments } from "@/api/equipment";
import { getGroups } from "@/api/group";
import { setGroupPerm, getResourceDetail, } from "@/api/group-permission";

export default {
  name: "space",
  data() {
    return {
      dialog: {
        title: "",
        visible: false,
        update: false,
      },
      perm: {
        title: "设置权限",
        visible: false,
      },
      statuses: [
        { key: 0, label: "停用" },
        { key: 1, label: "活动" },
        { key: 2, label: "草稿" },
        { key: 3, label: "审批中" },
        { key: 5, label: "由活动状态停用" },
        { key: 6, label: "由草稿状态停用" },
        { key: 7, label: "由审批状态停用" },
      ],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      search: {
        name: "",
        parentId: null,
      },
      spaces: [],
      datas: [],
      space: {
        id: null,
        spaceID: null,
        parentID: null,
        name: "",
        description: "",
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      },
      permissions: [],
      groups: [],
      levels: [
        { key: 0, label: "无权限" },
        { key: 2, label: "查看数据" },
        { key: 4, label: "修改对象" },
        { key: 8, label: "修改下级对象" },
      ],
      spacePerm: {
        id: null,
        permissionID: null,
        groupID: null,
        resourceID: 0,
        allowPermission: 0,
        denyPermission: 0,
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      },
      rules: null,
      detail: {
        select: [],
        id: null,
        groupid: null,
      },
      details: [],
      perms: [],
      // 查看所有位置
      childrenTable: [],
      children: {
        title: "所有设备",
        visible: false,
      },
      spacesModel: [],
      spaceProps: {
        lazy: false,
        multiple: false,
        checkStrictly: true,
      },
    };
  },
  created() {
    const vm = this;
    vm.$nextTick(() => {
      vm.getDatas(0, 0);
      getPermissions({ page: 0, size: 0 })
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.permissions.push({ key: d.id, label: d.name, hasPerm: 1 });
          }
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject();
        });
      getGroups({ page: 0, size: 0 })
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.groups.push({ key: d.id, label: d.name });
          }
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject();
        });
    });
  },
  computed: {
    options() {
      return this.$store.state.space.options
    },
  },
  mounted() {
    this.$store.dispatch('space/GetSpaces', { name: '', parentid: '', page: 0, size: 0 })
  },
  destroyed() {},
  methods: {
    getDatas(pageNo, pageSize) {
      const vm = this;
      getSpaces({
        name: vm.search.name,
        parentid: vm.search.parentId,
        page: pageNo,
        size: pageSize,
      })
        .then((res) => {
          vm.datas = this.toTree(res.data);
          vm.total = vm.datas.length;
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject(err);
        });
    },
    toTree(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach((item) => {
        delete item.children;
      });
      let map = {};
      data.forEach((item) => {
        map[item.spaceID] = item;
      });
      data.forEach((item) => {
        let parent = map[item.parentID];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    addData() {
      this.dialog.title = "添加位置";
      this.dialog.visible = true;
      this.dialog.update = false;
      this.space = {
        id: null,
        spaceID: null,
        parentID: null,
        name: "",
        description: "",
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      };
    },
    showDialog(row) {
      this.dialog.title = "修改位置";
      this.dialog.visible = true;
      this.dialog.update = true;
      this.spacesModel = this.getModel(row.spaceID);
      this.space = {
        id: row.id,
        spaceID: row.spaceID,
        parentID: row.parentID,
        name: row.name,
        description: row.description,
        statusID: row.statusID,
        employeeID_Update: this.$store.getters.uid,
      };
    },
    onDelete(row) {
      const vm = this;
      vm.$confirm("是否删除?", "提示信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((action) => {
        if (action === "confirm") {
          deleteSpace({ ids: row.spaceID })
            .then((res) => {
              vm.$message({
                message: res.message,
                type: "success",
              });
              Promise.resolve();
            })
            .catch((err) => {
              Promise.reject(err);
            });
        }
      });
      vm.getDatas(vm.pageNo, vm.pageSize);
    },
    handleRightChange(old_keys, new_keys) {
      const vm = this;
      if (new_keys && new_keys.length > 0) {
        vm.detail.groupid = new_keys[new_keys.length - 1];
      }
      vm.permissions.forEach((ele) => {
        ele.hasPerm = 1;
      });
      vm.details.forEach((element) => {
        if (element.id == vm.detail.groupid) {
          vm.permissions.forEach((ele) => {
            element.pdList.forEach((e) => {
              if (ele.key == e.permissionID) {
                ele.hasPerm = e.allowPermission;
              }
              let index = vm.perms.findIndex(
                (p) =>
                  p.groupID == e.groupID && p.permissionID == e.permissionID
              );
              if (index == -1) {
                vm.perms.push(e);
              }
            });
          });
        }
      });
      vm.permissions.forEach((ele) => {
        let perm = {
          id: 0,
          permissionID: ele.key,
          groupID: vm.detail.groupid,
          resourceID: vm.detail.id,
          allowPermission: ele.hasPerm ? 1 : 0,
          denyPermission: ele.hasPerm ? 0 : 1,
          statusID: 1,
          employeeID_Update: vm.$store.getters.uid,
        };
        let index = vm.perms.findIndex(
          (p) =>
            p.groupID == perm.groupID && p.permissionID == perm.permissionID
        );
        if (index == -1) {
          vm.perms.push(perm);
        }
      });
    },
    handleRadioChange(val) {
      const vm = this;
      if (vm.permissions && vm.permissions.length > 0) {
        vm.permissions.forEach((e) => {
          let perm = {
            id: 0,
            permissionID: e.key,
            groupID: vm.detail.groupid,
            resourceID: vm.detail.id,
            allowPermission: e.hasPerm ? 1 : 0,
            denyPermission: e.hasPerm ? 0 : 1,
            statusID: 1,
            employeeID_Update: vm.$store.getters.uid,
          };
          let has = false;
          for (let i = 0; i < vm.perms.length; i++) {
            if (
              vm.perms[i].groupID == perm.groupID &&
              vm.perms[i].permissionID == perm.permissionID
            ) {
              vm.perms[i].allowPermission = perm.allowPermission;
              vm.perms[i].denyPermission = perm.denyPermission;
              has = true;
              break;
            }
          }
          if (!has) {
            vm.perms.push(perm);
          }
        });
      }
    },
    dateFormat(date) {
      if (typeof date == 'string') {
        date = date.replace("T", " ");
        return date.split(".")[0];
      }
    },
    handlePermission(row) {
      const vm = this;
      vm.perm.visible = true;
      vm.detail.id = row.spaceID;
      vm.detail.groupid = null;
      vm.perms = [];
      getResourceDetail({ id: vm.detail.id }).then((res) => {
        vm.details = [];
        vm.detail.select = [];
        if (res.data && res.data instanceof Array) {
          vm.details = res.data;
          res.data.forEach((e) => {
            if (e.id) {
              vm.detail.select.push(e.id);
            }
          });
        }
      });
      vm.permissions.forEach((ele) => {
        ele.hasPerm = 1;
      });
    },
    handleCancel() {
      this.perm.visible = false;
    },
    handleConfirm() {
      const vm = this;
      setGroupPerm({ data: JSON.stringify(vm.perms) }).then((res) => {
        vm.perm.visible = false;
        vm.$message({
          message: res.message,
          type: "success",
        });
        Promise.resolve();
      });
      console.info(vm.perms);
    },
    cancelClick() {
      this.dialog.visible = false;
    },
    confirmClick() {
      const vm = this;
      if (!vm.dialog.update) {
        addSpace(vm.space).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas(vm.pageNo, vm.pageSize);
        });
      } else {
        updateSpace(vm.space).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas(vm.pageNo, vm.pageSize);
        });
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handlePageChange(val) {
      const vm = this;
      vm.pageNo = val;
      vm.getDatas(vm.pageNo, vm.pageSize);
    },
    // 查看所有成员
    lookChildren(row) {
      let vm = this;
      vm.children.title = row.name + "的设备";
      vm.children.visible = true;
      getEquipments({
        name: "",
        spaceId: row.spaceID,
        modeId: "",
        page: 0,
        size: 1000,
      }).then((res) => {
        if (res.data) {
          vm.childrenTable = res.data;
        }
      });
    },
    // 选择位置
    spaceChange(val) {
      if (val.length > 0) {
        this.space.ParentID = val[val.length - 1];
      } else {
        this.space.ParentID = null;
      }
    },
    selectChange(val) {
      if (val.length > 0) {
        this.search.parentId = val[val.length - 1];
      } else {
        this.search.parentId = null
      }
    },
    getModel(id) {
      let model = [];
      let isFind = 0;
      const func = (id, arr, h) => {
        arr.forEach(e => {
          if (isFind) {
            return;
          }
          while (model.length > h) {
            model.pop();
          }
          if (e.value == id) {
            isFind = 1;
            model.push(e.value);
            return model;
          } else if (e.children) {
            model.push(e.value);
            func(id, e.children, h + 1);
          }
        })
      }
      func(id, this.options, 0);
      return model;
    },
  },
};
</script>

<style lang="scss" scoped>
.space {
  width: 100%;
  padding: 30px;
  .header {
    margin-bottom: 20px;
  }
  .content {
    margin-bottom: 20px;
  }
  .pagination {
    margin-top: 20px;
  }
}
</style>